<template>
    <div class="tabsItemBox" v-loading="loading">
        <div class="selftTableBtn" v-if="selftTablePage">
            <el-button size="mini" type="primary" @click="toAddTable"
                >新增课表</el-button
            >
            <el-button
                size="mini"
                type="danger"
                @click="delThisWeek"
                v-if="trDateList.length !== 0"
                >删除课表</el-button
            >
        </div>
        <div class="selectState">
            <div class="selectItem" v-if="isShowGradeOptions && tableType != 2">
                <el-select
                    v-model="selectGradeIndex"
                    placeholder="班级"
                    size="mini"
                    @change="changeGrade"
                    :disabled="gradeDataList.length === 0"
                >
                    <el-option
                        v-for="(item, index) in gradeDataList"
                        :key="index"
                        :label="item.group_name"
                        :value="index"
                    >
                    </el-option>
                </el-select>
            </div>
            <div class="selectItem">
                <el-select
                    v-model="selectSemesterIndex"
                    :placeholder="yearPlaceholder"
                    size="mini"
                    @change="changeSemester"
                    :disabled="semesterDataList.length === 0"
                >
                    <el-option
                        v-for="(item, index) in semesterDataList"
                        :key="item.semester_name"
                        :label="item.semester_name"
                        :value="index"
                    >
                    </el-option>
                </el-select>
            </div>
            <div class="selectItem">
                <el-select
                    v-model="selectWeekIndex"
                    placeholder="周次"
                    size="mini"
                    @change="changeWeek"
                    :disabled="weekDataList.length === 0"
                >
                    <el-option
                        v-for="(item, index) in weekDataList"
                        :key="item.week_name"
                        :label="item.week_name"
                        :value="index"
                    >
                    </el-option>
                </el-select>
            </div>
        </div>
        <div class="classTableBox" v-if="trDateList.length !== 0">
            <div class="classTableBoxTr">
                <div
                    v-for="(item, index) in trDateList"
                    class="classtableitemTitle"
                    :key="index"
                >
                    周{{ weekVaule[index] }}
                    <div class="titleDate">{{ item | trDate }}</div>
                </div>
            </div>
            <div class="classTableBoxTr">
                <div
                    v-for="(l, dayIndex) in showTableList"
                    :key="dayIndex"
                    style="width: 13.8%;"
                >
                    <!-- min-width: 155px; -->
                    <div
                        v-for="(i, index) in lessonList"
                        class="classtableitem"
                        :key="index"
                        :style="[
                            {
                                background: l[index].isNow ? '#19da62' : ''
                            },
                            { color: l[index].isNow ? '#FFF' : '#9FA3B0' }
                        ]"
                    >
                        <div>
                            ({{ i.lesson_start | toGetTime }}~{{
                                i.lesson_end | toGetTime
                            }})
                        </div>
                        <div class="thisClassName">
                            {{ l[index].subject_name }}
                        </div>
                        <div class="startImg" @click="detailsView(l[index], i)">
                            <div
                                class="noStarImg"
                                :style="[
                                    {
                                        background: l[index].isOverdue
                                    }
                                ]"
                            ></div>
                        </div>
                        <div v-if="l[index].teacher_name">
                            老师:{{ l[index].teacher_name }}
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <Tips v-else :tipsText="'当前暂无课表'"> </Tips>
        <!-- //弹窗 -->
        <el-dialog
            custom-class="dialogBorder3"
            :visible.sync="dialogShow"
            width="400px"
            :before-close="handleClose"
            :title="dialogData.className"
        >
            <div class="subInfoText">
                时间：<span>{{ dialogData.classTime }}</span>
            </div>
            <div class="subInfoText" v-if="tableType != 2">
                老师：<span>{{ dialogData.teacherName }}</span>
            </div>
            <div class="subInfoText" v-if="tableType != 2">
                教室：<span>{{ dialogData.roomName }}</span>
            </div>
            <div class="subInfoText" v-if="tableType != 2">
                状态：<span>{{ dialogData.state }}</span>
            </div>
            <div class="subInfoText">
                备注：<span>{{ dialogData.remark }}</span>
            </div>
            <span slot="footer" class="dialog-footer">
                <div
                    @click="dgClose"
                    class="dialogBtn dialogBtn-blue"
                    v-if="tableType != 2"
                >
                    取消
                </div>
                <div
                    @click="to_course_sign"
                    class="dialogBtn dialogBtn-green"
                    v-if="tableType != 2"
                >
                    签到
                </div>
                <!-- 前往课堂 -->
                <div
                    @click="dgClose"
                    class="dialogBtn dialogBtn-green"
                    v-if="tableType == 2"
                >
                    确定
                </div>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    getSemester,
    getWeekList,
    getScheduleWeekInfo,
    getLessonTime,
    getSignWeek,
    toCourseSign,
    getPersonSemester,
    getPersonWeekList,
    getPersonScheduleWeekInfo,
    getPersonLessonTime,
    toWeekDelete
} from "@/api/table";
import { getBetweenDateStr, getFormatTime } from "@/utils/timeUtils";

import Tips from "@/components/tips";
export default {
    components: {
        Tips
    },
    props: {
        //班级列表
        gradeDataList: {
            type: Array,
            default: () => {
                return [];
            }
        },
        //单只需单个班级时隐藏，传入单班级数组即可，否则默认第一个班级
        isShowGradeOptions: {
            type: Boolean,
            default: true
        },
        // 课表类型 1 班级课表， 2 自订课表
        tableType: {
            type: Number,
            default: 1
        },
        //个人课表页面
        selftTablePage: {
            type: Boolean,
            default: false
        }
    },
    watch: {
        gradeDataList() {
            if (this.gradeDataList.length === 0) {
                this.$message({
                    message: "您还没有加入班级",
                    type: "warning"
                });
                this.trDateList = [];
                this.semesterDataList = [];
                this.weekDataList = [];
                this.loading = false;
                return;
            } else {
                this.loading = true;
                this.selectGradeIndex = 0;
                this.get_semester_list();
            }
        },
        tableType: {
            handler(value) {
                if (value == 1) {
                    this.yearPlaceholder = "学期名称";
                } else if (value == 2) {
                    this.loading = true;
                    this.yearPlaceholder = "年度名称";
                    this.get_semester_list();
                }
            },
            immediate: true
        }
    },
    data() {
        return {
            yearPlaceholder: "学期名称", //学年显示提示
            weekVaule: ["一", "二", "三", "四", "五", "六", "日"], //星期显示
            semesterDataList: [], //学期列表
            weekDataList: [], //周列表
            selectGradeIndex: "", //选择班级
            selectSemesterIndex: "", //选择学期
            selectWeekIndex: "", //选择周次
            trDateList: [], //表头
            lessonList: [], //时间列表
            showTableList: [], //渲染课表
            weekSignList: [], //周签到列表
            loading: false,
            dialogShow: false, //弹窗
            dialogData: {}, //弹窗详情
            myCourseId: "" //自订课表删除id缓存
        };
    },
    filters: {
        trDate: function(value) {
            value = value.split("-");
            return value[1] + "." + value[2];
        },
        toGetTime: function(value) {
            value = value.split(":");
            return value[0] + ":" + value[1];
        }
    },
    methods: {
        //获取班级学期
        async get_semester_list() {
            var dataList;
            if (this.tableType == 2) {
                /**
                 * 获取当前自订学年
                 */
                var personSemesterData = await getPersonSemester({
                    usr_id: this.$store.getters.userInfo.id,
                    limit: 999
                });
                dataList = personSemesterData.data.list;
            } else {
                /**
                 * 获取当前所在的学期
                 */
                var semesterData = await getSemester({
                    school_id: this.gradeDataList[this.selectGradeIndex]
                        .parent_id,
                    class_id: this.gradeDataList[this.selectGradeIndex].groupid
                });
                dataList = semesterData.data;
            }

            if (dataList.length === 0) {
                this.loading = false;
                var title = "该班级还未添加学期列表或当前周没有课程";
                if (this.tableType == 2) {
                    title = "当前还未添加年度列表";
                }
                this.$message({
                    message: title,
                    type: "warning"
                });
                this.trDateList = [];
                this.semesterDataList = [];
                this.weekDataList = [];
                this.selectSemesterIndex = "";
                this.selectWeekIndex = "";
                return;
            } else {
                this.selectSemesterIndex = 0;
                this.semesterDataList = dataList;
                //获取本学期
                dataList.forEach((el, index) => {
                    var date_start = new Date(el.semester_start).getTime();
                    //结束时间
                    var date_end = new Date(el.semester_end).getTime();
                    //此时时间
                    var date_now = new Date().getTime();

                    if (date_start <= date_now && date_now < date_end) {
                        this.selectSemesterIndex = index;
                    } else {
                        this.selectSemesterIndex = 0;
                    }
                });
                this.get_week_list();
            }
        },
        //获取周列表
        async get_week_list() {
            if (this.semesterDataList.length === 0) {
                return;
            }
            var listData;
            if (this.tableType == 2) {
                /**
                 * 获取自订周列表
                 */
                var personWeekData = await getPersonWeekList({
                    semester_id: this.semesterDataList[this.selectSemesterIndex]
                        .unid
                });
                listData = personWeekData.data;
            } else {
                /**
                 * 获取周列表
                 */
                var weekData = await getWeekList({
                    semester_id: this.semesterDataList[this.selectSemesterIndex]
                        .unid
                });
                listData = weekData.data;
            }

            if (listData.length === 0) {
                this.loading = false;
                this.$message({
                    message: "该班级还未添加周期列表",
                    type: "warning"
                });
                this.trDateList = [];
                this.weekDataList = [];
                this.selectWeekIndex = "";
                return;
            } else {
                this.selectWeekIndex = 0;
                this.weekDataList = listData;
                //获取本周
                listData.forEach((el, index) => {
                    var date_start = new Date(el.week_start).getTime();
                    //结束时间
                    var date_end = new Date(el.week_end).getTime();
                    //此时时间
                    var date_now = new Date().getTime();

                    if (date_start <= date_now && date_now < date_end) {
                        this.selectWeekIndex = index;
                    }
                });
                this.get_week_class_info();
            }
        },
        //获取课表
        async get_week_class_info() {
            if (this.weekDataList.length === 0) {
                return;
            }

            var listData;
            if (this.tableType == 2) {
                /**
                 * 查询自订课表详情
                 */
                var personWeekClassInfo = await getPersonScheduleWeekInfo({
                    semester_week_id: this.weekDataList[this.selectWeekIndex]
                        .unid,
                    usr_id: this.$store.getters.userInfo.id
                });
                listData = personWeekClassInfo.data;
                if (listData.length != 0) {
                    this.myCourseId = listData[0].unid;
                }
            } else {
                //获取课表
                /**
                 * 查询课表详情(ScheduleWeek)
                 */
                var weekClassInfo = await getScheduleWeekInfo({
                    semester_week_id: this.weekDataList[this.selectWeekIndex]
                        .unid,
                    class_id: this.gradeDataList[this.selectGradeIndex].groupid
                });
                listData = weekClassInfo.data;
            }

            if (listData.length === 0) {
                this.loading = false;
                if (this.tableType == 1) {
                    this.$message({
                        message: "该班级还未录入课表",
                        type: "warning"
                    });
                }

                this.trDateList = [];
                return;
            }

            //获取时间段信息
            var lessonListData;
            if (this.tableType == 2) {
                /**
                 * 获取自订时间段信息(lessonTime)
                 */
                var personLessonData = await getPersonLessonTime({
                    time_main_id: listData[0].time_main_id
                });

                lessonListData = personLessonData.data.list;
            } else {
                /**
                 * 获取时间段信息(lessonTime)
                 */
                var lessonData = await getLessonTime({
                    time_main_id: listData[0].time_main_id
                });
                lessonListData = lessonData.data;
            }

            this.lessonList = lessonListData;

            //班级课表才有签到记录
            if (this.tableType == 1) {
                await this.get_sign_week();
            }

            //先算出表头
            var weekData = this.weekDataList[this.selectWeekIndex];
            var sTIME = new Date(weekData.week_start).getTime();
            var eTIME = new Date(weekData.week_end).getTime();
            var sevenTime = 6 * 24 * 60 * 60 * 1000;
            // 不够7天补足他
            if (eTIME - sTIME < sevenTime) {
                var newEnd = sTIME + sevenTime;
                weekData.week_end = getFormatTime(newEnd, false);
            }
            var trData = getBetweenDateStr(
                weekData.week_start,
                weekData.week_end
            );
            this.trDateList = trData;
            /**
             * 先找周，有开始时间，结束时间，动态计算出周一到周日对应的日期
             * 找课表，拿取期中一个的time_main_id获取到课节对应时间
             * 课节的uid对应课表的time_lesson_id，day对应周几
             * 最后动态算出课表位置，生成课表
             *
             * 再获取本周签到记录判断用户状态
             */
            var showTableData = [];
            let classInfoArr = listData;
            var lessonInfoList = lessonListData;
            //第一次筛选，同一天数据集合
            for (let dayIndex = 0; dayIndex < 7; dayIndex++) {
                let arr = [];
                classInfoArr.forEach(classEl => {
                    if (classEl.day === dayIndex + 1) {
                        arr.push(classEl);
                    }
                });
                showTableData.push(arr);
            }
            //第二次筛选，排序
            showTableData.forEach((el, index) => {
                var arr = new Array(lessonInfoList.length).fill({});
                lessonInfoList.forEach((lessonEl, lessonIndex) => {
                    el.forEach(item => {
                        if (item.time_lesson_id === lessonEl.unid) {
                            arr[lessonIndex] = item;
                            //开始时间
                            var date_start = new Date(
                                trData[index] + " " + lessonEl.lesson_start
                            ).getTime();
                            //结束时间
                            var date_end = new Date(
                                trData[index] + " " + lessonEl.lesson_end
                            ).getTime();
                            //此时时间
                            var date_now = new Date().getTime();
                            if (date_start <= date_now && date_now < date_end) {
                                arr[lessonIndex].isNow = true;
                                arr[lessonIndex].isOverdue = "";
                            }
                            //过期了
                            if (date_end < date_now) {
                                arr[lessonIndex].isNow = false;
                                arr[lessonIndex].isOverdue = this.stateColor(
                                    arr[lessonIndex]
                                );
                            }
                            if (date_start > date_now) {
                                arr[lessonIndex].isNow = false;
                                arr[lessonIndex].isOverdue = "";
                            }
                        }
                    });
                });
                showTableData[index] = arr;
            });
            console.log("====================================");
            console.log("最终课表：", showTableData);
            console.log("====================================");
            this.showTableList = showTableData;
            //
            this.loading = false;
        },
        async get_sign_week() {
            if (this.weekDataList.length === 0) {
                return;
            }
            var signData = await getSignWeek({
                semester_week_id: this.weekDataList[this.selectWeekIndex].unid,
                usr_id: this.$store.getters.userInfo.id,
                class_id: this.gradeDataList[this.selectGradeIndex].groupid
            });
            this.weekSignList = signData.data;
        },
        /**
         * 点击详情
         * @param {Object}item 当前课程，
         * @param {Object}time 当前时间段，
         */
        detailsView(item, time) {
            if (!item.subject_name) {
                return;
            }
            this.dialogShow = true;
            var start_time = time.lesson_start.split(":");
            var end_time = time.lesson_end.split(":");
            if (this.tableType == 2) {
                this.dialogData = {
                    className: item.subject_name,
                    classTime:
                        start_time[0] +
                        ":" +
                        start_time[1] +
                        " - " +
                        end_time[0] +
                        ":" +
                        end_time[1],
                    remark: item.remark || "无备注"
                };
                return;
            }
            var signArr = this.weekSignList.filter(el => {
                return (
                    el.day === item.day &&
                    el.time_lesson_id === item.time_lesson_id
                );
            });
            if (signArr.length === 0) {
                signArr.push({
                    sign_type: "无"
                });
            }

            this.dialogData = {
                className: item.subject_name,
                classTime:
                    start_time[0] +
                    ":" +
                    start_time[1] +
                    " - " +
                    end_time[0] +
                    ":" +
                    end_time[1],
                teacherName: item.teacher_name,
                roomName: this.gradeDataList[this.selectGradeIndex].group_name,
                state:
                    signArr[0].sign_type === 1
                        ? "已签到"
                        : signArr[0].sign_type === 2
                        ? "迟到"
                        : "未签到",
                remark: item.remark || "无备注",
                semester_week_id: this.weekDataList[this.selectWeekIndex].unid,
                time_lesson_id: time.unid,
                usr_id: this.$store.getters.userInfo.id,
                class_id: item.class_id
            };
        },
        async to_course_sign() {
            var couData = await toCourseSign({
                semester_week_id: this.dialogData.semester_week_id,
                time_lesson_id: this.dialogData.time_lesson_id,
                usr_id: this.dialogData.usr_id,
                class_id: this.dialogData.class_id
            });
            if (couData.code === 200) {
                this.get_sign_week();
                this.$message({
                    message: couData.message,
                    customClass: "customClass",
                    type: "success"
                });
            }
            this.dialogShow = false;
        },
        //个人课表页面删除周课表
        delThisWeek() {
            console.log("删除这周课表：", this.myCourseId);
            this.$confirm("此操作将删除该课表, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(async () => {
                    var query = {
                        unid: this.myCourseId
                    };
                    var list = await toWeekDelete(query);
                    if (list.code == 200) {
                        this.loading = true;
                        this.get_semester_list();
                        this.$message({
                            type: "success",
                            customClass: "customClass",
                            message: "删除成功!"
                        });
                    }
                    console.log("删除课表：", list);
                })
                .catch(() => {});
        },
        toAddTable() {
            this.$router.push("/personalCenter/addSelfTable");
        },
        //切换班级
        changeGrade() {
            this.loading = true;
            this.get_semester_list();
        },
        //切换学期
        changeSemester() {
            this.loading = true;
            this.get_week_list();
        },
        //切换周次
        changeWeek() {
            this.loading = true;
            this.get_week_class_info();
        },
        handleClose(done) {
            done();
        },
        dgClose() {
            this.dialogShow = false;
        },
        //根据状态改变颜色
        stateColor(item) {
            if (this.weekSignList.length == 0) {
                return "#f04c28";
            }
            var signArr = this.weekSignList.filter(el => {
                return (
                    el.day === item.day &&
                    el.time_lesson_id === item.time_lesson_id
                );
            });
            if (signArr.length == 0) {
                return "#f04c28";
            }
            var color =
                signArr[0].sign_type === 1
                    ? "#018854"
                    : signArr[0].sign_type === 2
                    ? "#f3d017"
                    : "#f04c28";
            return color;
        }
    }
};
</script>

<style scoped lang="scss">
.tabsItemBox {
    width: 100%;
    // height: 830px;
    background-color: #ffffff;
    border-radius: 8px;
    margin-top: 15px;
    padding: 17px;
    box-sizing: border-box;

    .selectState {
        display: flex;
        margin: 10px 5px;

        .selectItem {
            width: 115px;
            margin-right: 10px;
        }
    }
}

.classTableBox {
    width: 100%;
    margin-top: 27px;

    .classTableBoxTr {
        width: 100%;
        display: flex;
        justify-content: space-around;
    }

    .classtableitemTitle {
        width: 13.8%;
        // min-width: 156.58px;
        text-align: center;
        color: #333;
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 10px;
        .titleDate {
            font-size: 13px;
            font-weight: normal;
            color: #9fa3b0;
        }
    }

    .classtableitem {
        width: 100%;
        // min-width: 155px;
        height: 110px;
        text-align: center;
        color: #9fa3b0;
        border-radius: 8px;
        margin-bottom: 8px;
        font-size: 12px;
        overflow: hidden;
        background: #f4fdff;
        background-size: 100% 100%;
        padding: 7px;
        box-sizing: border-box;
    }

    .thisClassName {
        font-size: 16px;
    }

    .startImg {
        width: 31px;
        height: 31px;
        margin: 4px auto;
        padding-top: 11px;
        cursor: pointer;
        box-sizing: border-box;
    }

    .noStarImg {
        width: 9px;
        height: 9px;
        background: #dadfe6;
        border-radius: 50%;
        margin: 0 auto;
    }
}

.dialogBorder3 {
    .subInfoText {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.65);
        margin-top: 8px;
        margin-left: 15px;

        span {
            color: #333;
        }
    }

    /* 弹窗按钮 */
    .dialogBtn {
        display: inline-block;
        width: 65px;
        height: 32px;
        line-height: 32px;
        border-radius: 16px;
        text-align: center;
        border: 1px #000000 solid;
        margin-left: 5px;
        padding: 0 10px;
        font-size: 12px;
        cursor: pointer;
    }

    .dialogBtn-blue {
        color: #3980ed;
        background: #ffffff;
        border-color: #3980ed;
    }

    .dialogBtn-green {
        background: #18db60;
        color: #ffffff;
        border-color: #15ca57;
    }
}

.selftTableBtn {
    width: 100%;
    text-align: right;
}
</style>
